package com.ifcar.app.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.webkit.WebView;

import com.ifcar.app.rss.GetColumnsInfo;
import com.netease.util.Pair;

public class NewsPageHelper {
	
	// 一级标题
	public static final String H1_TAG = "<!--@@H1-->";
	// 描述
	public static final String PRE_TAG = "<!--@@PRE-->";
	// 二级标题
	public static final String H2_TAG = "<!--@@H2-->";
	// 结语
	public static final String END_TAG = "<!--@@END-->";
	
	public static final String SPECIAL_TAG = "special";
	
	/**
	 * 获取正文内容 
	 * @param context 
	 * @param webView
	 * @param map
	 * @param isMore 是否为更多内容
	 * @param preImageCount head map 中的图片个数
	 * @param preLinkCount head map 中的链接个数
	 * @param isDownloadPic
	 * @param screentype
	 * @param htmlWidth
	 * @return
	 */
	public static String getBody(final Context context, final WebView webView, final Map<String, Object> map, 
			boolean isMore, int preImageCount, int preLinkCount, final boolean isDownloadPic, final int screentype,
			final int htmlWidth) {
		
		if (null != map && map.get(GetColumnsInfo.BODY_TAG) != null) {
			
			String body = map.get(GetColumnsInfo.BODY_TAG).toString();
			
			// 格式化新闻内部链接
			body = formatLink(map, body, isMore, preLinkCount);
			
			// 格式化新闻图片和视频图片
			body = formatImageAndVideo(map, isMore, preImageCount, context, webView, 
					body, isDownloadPic, screentype, htmlWidth);
			
			// 格式化策划新闻
			String template = (String) map.get(GetColumnsInfo.TEMPLATE_TAG);
			if(SPECIAL_TAG.equals(template)){
				body = formatSpecial(map, body);
			}
			
			return body;
			
		}
		return "";
	}
	
	/**
	 * 格式化文章正文的链接
	 * @param map
	 * @param body
	 */
	private static String formatLink(final Map<String, Object> map, String body, boolean isMore, int preLinkCount) {
		
		Object obj = map.get(GetColumnsInfo.LINK_TAG);
		if (obj != null && null != body) {
			
			List<Map<String, Object>> linkList = (List<Map<String, Object>>) obj;
			
			for (int i = 0; i < linkList.size(); i++) {
				Map<String, Object> linkMap = linkList.get(i);
				String ref = (String) linkMap.get(GetColumnsInfo.REF_TAG);
				String title = (String) linkMap.get(GetColumnsInfo.TITLE_TAG);
				int refindex = body.indexOf(ref);
				if (refindex != -1) {
					body = body.replace(body.substring(refindex,
							refindex + ref.length()), "<a style='color:#297997;' onclick='toLink("
									+ (isMore ? preLinkCount + i : i) + ");'><u>" + title + "</u></a>");
				}
			}
		}
		
		return body;
	}
	
	/**
	 * 格式化图片和视频图片
	 * @param map
	 * @param isMore
	 * @param preImgCount
	 * @param context
	 * @param webView
	 * @param body
	 * @param isDownloadPic
	 * @param screentype
	 * @param htmlWidth
	 * @return
	 */
	private static String formatImageAndVideo(final Map<String, Object>map, final boolean isMore, final int preImgCount,
			final Context context, final WebView webView, String body, boolean isDownloadPic, 
			final int screentype, final int htmlWidth){
		final ThemeSettingsHelper themeSettingsHelper = ThemeSettingsHelper.getThemeSettingsHelper(context);
		if (map.get(GetColumnsInfo.IMG_TAG) != null || map.get(GetColumnsInfo.VIDEO_TAG) != null) {
			
			List<Map<String, Object>> imageList = (List<Map<String, Object>>) map.get(GetColumnsInfo.IMG_TAG);
			List<Map<String, Object>> videoList = (List<Map<String, Object>>) map.get(GetColumnsInfo.VIDEO_TAG);
			
			List<Map<String, Object>> mediaList = new ArrayList<Map<String, Object>>();
			if(null != imageList && imageList.size() > 0){
				mediaList.addAll(imageList);
			}
			if(null != videoList && videoList.size() > 0){
				mediaList.addAll(videoList);
			}
			
			int len = mediaList.size();
			
			for (int i = 0; i < len; i++) {
				Map<String, Object> linkMap = mediaList.get(i);
				
				final String mediaType = (String) linkMap.get(GetColumnsInfo.MEDIA_TYPE);
				String url = "", tag = "";
				
				boolean isPhotoSet = !TextUtils.isEmpty( (String) linkMap.get(GetColumnsInfo.PHOTOSET_ID_TAG));
				boolean p = false;
				if(null != map.get(GetColumnsInfo.PICNAWS_TAG)){
					p = (Boolean) map.get(GetColumnsInfo.PICNAWS_TAG);
				}
				final boolean isPicNews = p;
				
				tag = (String) linkMap.get(GetColumnsInfo.REF_TAG);
				if(GetColumnsInfo.MEDIA_VIDEO.equals(mediaType)){ // 视频
					url = (String) linkMap.get(GetColumnsInfo.COVER_TAG);
				} else { // 图片
					url = (String) linkMap.get(GetColumnsInfo.SRC_TAG);
				}
				
				if (!StringUtil.isExactPicUrl(url)) continue;
				
				Pair<String, String> pair = getImgDownloadUrl(url, screentype);
				
				final String imgSrc = pair.first;
				final String imgName = pair.second;
				
				final int index = i;
				
				if (!PicUtil.isLocalPicExit(imgName.replace("_small", ""))) { // 获取网络图片
					if (!Tools.isshowimg(isDownloadPic, context)) continue;
					
					try {
						new AsyncTask<String, Void, Boolean>() {

							private String imgurl = "";
							
							@Override
							protected Boolean doInBackground(
									String... params) {
								// TODO Auto-generated method stub
								boolean result = false;
								imgurl = params[0];
								Bitmap bitmap = PicUtil.getBitMapForStringURL(imgurl.replace("_small", ""), context);
								if (PicUtil.saveMyBitmap(imgName.replace("_small", ""), bitmap)) {
									
									result = cutSmallBitmap(context, imgName, bitmap, isPicNews, htmlWidth);
									
									if(null != bitmap){
										bitmap.recycle();
										bitmap = null;
									}
								}
								return result;
							}

							@Override
							protected void onPostExecute(Boolean result) {
								// TODO Auto-generated method stub
								super.onPostExecute(result);

								if (result) {
									webView.loadUrl(applyPicToDoc((isMore ? preImgCount + index : index),PicUtil.phototempDir + imgName));
								} else if(Tools.CheckNetwork(context)){
									String host = Tools.getHostbyWAP(context);
									if (null != host) {
										WebView.enablePlatformNotifications();
										webView.setHttpAuthUsernamePassword(host, "80", "", "");
									}
									webView.loadUrl(applyPicToDoc((isMore ? preImgCount + index : index),imgurl.replace("_small","")));
								}
							}
							
						}.execute(imgSrc);

					} catch (Exception e) {
						e.printStackTrace();
					}
					
					int tagIndex = body.indexOf(tag);
					if (tagIndex != -1) {
						body = body.replace(body.substring(tagIndex, tagIndex + tag.length()), 
								displayPicInDoc(!themeSettingsHelper.isNightTheme(context), (isMore ? preImgCount + i : i), PicUtil.phototempDir + imgName, isPhotoSet, isPicNews, mediaType));
					}
				} else {
					int tagIndex = body.indexOf(tag);
					if (tagIndex != -1) {
						
						body = body.replace(body.substring(tagIndex, tagIndex + tag.length()), 
								displayPicInDoc(!themeSettingsHelper.isNightTheme(context), (isMore ? preImgCount + i : i), PicUtil.phototempDir + imgName, isPhotoSet, isPicNews, mediaType));
					}
				}

			}
		}
		return body;
	}
	
	/**
	 * <li>根据当前屏幕，拼接正文下载图片的url
	 * <li>返回Pair<String, String> first 为下载的图片url（包含了"_small"）,
	 * <li>second 为图片sdcard文件名称（包含"_small"）
	 * @param url
	 * @param screentype
	 * @return
	 */
	public static Pair<String, String> getImgDownloadUrl(String url, int screentype) {
		StringBuilder imgSrc = new StringBuilder(url);
		
		imgSrc.insert("http://".length(), "s.cimg.163.com/i/");
		if (1 == screentype) {
			imgSrc.append(".180x300.auto_small.jpg");
		} else if (2 == screentype) {
			imgSrc.append(".220x370.auto_small.jpg");
		} else {
			imgSrc.append(".420x740.auto_small.jpg");
		}
		
		String second = imgSrc.substring(imgSrc.lastIndexOf("/") + 1, imgSrc.length());
		
		return Pair.create(imgSrc.toString(), second);
	}

	static int picSize = 0;
	static int result_w = 0;
	static int result_h = 0;
	/**
	 * 根据媒体类型和是否是图片新闻，制作要显示的小图并且保存
	 * @param context
	 * @param imgName
	 * @param bitmap
	 * @param isPicNews
	 * @param htmlWidth
	 * @return
	 */
	protected static boolean cutSmallBitmap(Context context,  String imgName,
			Bitmap bitmap, boolean isPicNews, final int htmlWidth) {
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();
		Bitmap bm = null;
		
		int hw = (int) (htmlWidth * 0.9);
		if(isPicNews){
			picSize = Math.max(hw, 180);
			result_w = hw + (int) (hw * 0.2);
			result_h = 180 + (int) (180 * 0.2);;
		} else {
			picSize = 100;
			result_w = 100;
			result_h = 100;
		}
		boolean result = false;
		
		if (Math.min(w, h) > picSize) {
			if (w > h) {
				w = (int) (picSize * ((float) w / (float) h));
				h = picSize;
			} else {
				h = (int) (picSize * ((float) h / (float) w));
				w = picSize;
			}
			bm = PicUtil.resizeBitmap4DetailPage(context, bitmap, w, h, result_w, result_h);
		} else {
			bm = PicUtil.cutBitmap4DetailPage(bitmap, result_w, result_h);
		}
		
		result = PicUtil.saveMyBitmap(imgName, bm);
		
		if (null != bm) {
			bm.recycle();
			bm = null;
		}

        if(bitmap != null) {
        	bitmap.recycle();
        	bitmap = null;
        }
		return result;
	}

	/**
    * 将获得的图片渲染到文章中
    * @param currnetpic
    * @param localpic
    * @return
    */
	private static String applyPicToDoc(int currnetpic,String localpic){
		StringBuilder sb = new StringBuilder();
		
		// jquery 调用样式，现已删除jquery引用库
//		sb.append("javascript:(function() {$('#imgAdd_").append(currnetpic).append("').show();$('#imgContent_")
//		.append(currnetpic).append("').attr('src','").append(localpic).append("');})()");
		
		sb.append("javascript:setAddImgShowAndImgContent('").append(currnetpic).append("', '").append(localpic).append("');");
		
		return sb.toString();
	}
	
	/**
	 * 日间or夜间文章正文内嵌图片JavaScript代码片段
	 * @param theme ture 日间模式  false 夜间模式
	 * @param currnetpic
	 * @param localpic
	 * @param isPhotoSet
	 * @param isPicNews
	 * @param mediaType
	 * @return
	 */
	private static String displayPicInDoc(boolean theme,int currnetpic,String localpic,
			boolean isPhotoSet, boolean isPicNews, String mediaType){
		
		StringBuilder sb = new StringBuilder();
		String show_hide = "display:none;";
		String onclick = "zoomOut("+ currnetpic +"); ";
		
		if(!new File(localpic).exists()){
			show_hide = "display:none;";
			localpic = "null_src.png";
		}else{
			show_hide = "display:block;";
		}
		
		String imgOpacity = theme ? "" : "opacity:0.5;";
		String addOpacity = theme ? "" : "opacity:0.6;";
//		isPicNews = true;
		if(isPicNews){ // 大图新闻
			String backgroundImg = theme ? "big_detailpage_image_bk.png" : "night_big_detailpage_image_bk.png";
			
			if(GetColumnsInfo.MEDIA_VIDEO.equals(mediaType)){ // 视频
				String borderImg = "-webkit-border-image: url(" + backgroundImg + ") 2 2 2 3 stretch stretch; border-width:2px 2px 2px 3px;";
				
				sb.append("<div style='position:relative; width:95%; height:180px; text-align:center; margin:5px 10px 25px 10px;'")
				.append("id='largepic").append(currnetpic).append("' onclick=").append(onclick).append(">")
				.append("<img id='imgContent_").append(currnetpic).append("' src='").append(localpic)
				.append("' style='width: 95%; height: 100%; ").append(borderImg).append(imgOpacity).append("' />")
				.append("<img src='big_play.png' style='position:absolute; top:30%; left: 36%; width: 80px; height: 80px; ").append(addOpacity).append("' /></div>");
			} else { // 图片
				
				String imgContentSize = "width: 95%; height: 100%; ";
				String borderImg = "-webkit-border-image: url(" + backgroundImg + ") 2 2 2 3 stretch stretch; border-width:2px 2px 2px 3px;";
				String imgSetTag = "";
				if(isPhotoSet){
					backgroundImg = theme ? "big_detailpage_imageset_bk.png" : "night_big_detailpage_imageset_bk.png";
					borderImg = "-webkit-border-image: url(" + backgroundImg + ") 15 8 7 9 stretch stretch; border-width:15px 8px 7px 9px;";
					imgSetTag = "<img src='null_src.png' style='position:absolute; width:97.6%; height: 108%;  top:0%; left: 0%;  background-image: url(img_set_flag.png); background-repeat:no-repeat; background-position: bottom right; border: none;' />";
				}
				sb.append("<div style='position:relative; width:95%; height:180px; text-align:center; margin:5px 10px 25px 10px;").append(imgOpacity).append("' ")
				.append("id='largepic").append(currnetpic).append("' onclick=").append(onclick).append(">")
				.append("<img id='imgContent_").append(currnetpic).append("' src='").append(localpic)
				.append("' style='").append(borderImg).append(imgContentSize).append(imgOpacity).append("' />").append(imgSetTag).append(" </div>");
			}
		} else { // 普通新闻
			String backgroundImg = theme ? "detailpage_image_bk.png" : "night_detailpage_image_bk.png";
			
			if(GetColumnsInfo.MEDIA_VIDEO.equals(mediaType)){ // 视频
				
				String borderImg = "-webkit-border-image: url(" + backgroundImg + ")  2 2 4 4 stretch stretch; border-width:2px 2px 4px 4px;";
				
				sb.append("<div style='float:right; clear:both; position:relative; width:100px; height:100px; margin-left: 10px; margin-bottom: 10px; margin-right: 5px;' ")
				.append("id='largepic").append(currnetpic).append("' onclick=").append(onclick).append(">")
				.append("<img id='imgContent_").append(currnetpic).append("' src='").append(localpic)
				.append("' style='width: 95%; height: 95%; ").append(borderImg).append(imgOpacity).append("' />")
				.append("<img src='small_play.png' style='position:absolute; top:25%; left:25%; width:50px; height:50px; ")
				.append(addOpacity).append("' /></div>");
				
			} else { // 图片
				
				String externDivStyle = "width:100px; height:100px; ";
				String borderImg = "-webkit-border-image: url(" + backgroundImg + ") 2 2 4 4 stretch stretch; border-width:2px 2px 4px 4px;";
				if(isPhotoSet){
					backgroundImg = theme ? "detailpage_imageset_bk.png" : "night_detailpage_imageset_bk.png";
					externDivStyle = "width:120px; height:120px; ";
					borderImg = "-webkit-border-image: url(" + backgroundImg + ") 15 8 7 9 stretch stretch; border-width:15px 8px 7px 9px;";
				}
				
				sb.append("<div style='float:right; clear:both; position:relative; ").append(externDivStyle)
				.append(" margin-left: 10px; margin-bottom: 10px; margin-right: 5px; ").append(imgOpacity).append("' ")
				.append("id='largepic").append(currnetpic).append("' onclick=").append(onclick).append(">")
				.append("<img id='imgContent_").append(currnetpic).append("' src='").append(localpic).append("' style='width: 95%; height: 95%; ")
				.append(addOpacity).append(borderImg).append("' />");
				if(!isPhotoSet){
					sb.append("<img id='imgAdd_").append(currnetpic).append("' src=\"add.png\" style='position:absolute; top:85%; left: -5%; width:20px; height:20px;").append(show_hide).append(addOpacity).append("' />");
				} else { // 添加图集标示
					sb.append("<img src='null_src.png' style='position:absolute; width:102%; height: 108%;  top:0%; left: 0%;  background-image: url(img_set_s_flag.png); background-repeat:no-repeat; background-position: bottom right; border: none; ' />");
				}
				sb.append("</div>");
			}
		}
		
		return sb.toString();
	}
	
	private static String formatSpecial(Map<String, Object> map, String body) {
		
		StringBuilder sb = new StringBuilder(body);
		int h1Count = StringUtil.findRegexCount(sb, H1_TAG);
		int preCount = StringUtil.findRegexCount(sb, PRE_TAG);
		int h2Count = StringUtil.findRegexCount(sb, H2_TAG);
		int endCount = StringUtil.findRegexCount(sb, END_TAG);
		
		if(h1Count > 0 && h1Count % 2 == 0){ // 一级标题样式
			String START_INSERT = "<div class='h1style'>";
			String END_INSERT = "</div>";
			formatByTag(sb,	h1Count, START_INSERT, END_INSERT, H1_TAG);
		}
		
		// div + image
		if(preCount > 0 && preCount % 2 == 0){ // 简述样式
			String START_INSERT = "<div class='digeststyle'> <span class='digesttagstyle'>导语</span>";
			String END_INSERT = "</div>";
			formatByTag(sb,	preCount, START_INSERT, END_INSERT, PRE_TAG);
		}
		
		if(h2Count > 0 && h2Count % 2 == 0){ // 二级标题样式
			String START_INSERT = "<div class='h2style'>";
			String END_INSERT = "</div>";
			formatByTag(sb,	h2Count, START_INSERT, END_INSERT, H2_TAG);
		}
		
		if(endCount > 0 && endCount % 2 == 0){ // 结语样式
			String START_INSERT = "<div class='digeststyle'> <span class='digesttagstyle'>结语</span>";
			String END_INSERT = "</div>";
			formatByTag(sb,	endCount, START_INSERT, END_INSERT, END_TAG);
		}

//		sb.toString().replaceAll(H1_TAG, "");
//		sb.toString().replaceAll(PRE_TAG, "");
//		sb.toString().replaceAll(H2_TAG, "");
//		sb.toString().replaceAll(END_TAG, "");
//		System.out.println("sb:" + sb.toString());
		return sb.toString();
	}
	
	/**
	 * 格式化策划新闻的内容，相同的标示可以用此方法替换
	 * 需要事先知道body（sb）中有几个（count）要替换的标示（tag）
	 * @param sb 正文body
	 * @param count 需要替换的个数
	 * @param startInsert 开始标示
	 * @param endInsert 结束标示
	 * @param tag 被替换的标示
	 */
	private static void formatByTag(StringBuilder sb, int count, String startInsert, String endInsert, String tag) {
		
		try {
		
			int start = 0;
			for(int i = 0; i < count; i ++){
				if(i % 2 == 0){ // 开始标示
					
					int offset = sb.indexOf(tag, start);
					sb.insert(offset + tag.length(), startInsert);
					
					start = 0;
					start += offset + tag.length() + startInsert.length();
					
				} else { // 结束标示
					
					int offset = sb.indexOf(tag, start);
					sb.insert(offset, endInsert);
					
					start = 0;
					start += offset + tag.length() + endInsert.length();
					
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
